package com.qf.response;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应体处理器
 * @date 2020-09-25
 */
@ControllerAdvice(annotations = BaseResponse.class)
@Slf4j

public class ResponseResultHandlerAdvice implements ResponseBodyAdvice {
    @Autowired
    ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        log.info("returnType:" + returnType);
        log.info("converterType:" + converterType);
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof ResponseResult) { // 如果响应返回的对象为统一响应体，则直接返回body
            return body;
        } else {

//            if (body instanceof String) {
//                try {
//                    return  objectMapper.writeValueAsString( new ResponseResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), body));
//                } catch (JsonProcessingException e) {
//                    e.printStackTrace();
//                }
//            }
            // 只有正常返回的结果才会进入这个判断流程，所以返回正常成功的状态码
            ResponseResult responseResult = new ResponseResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), body);
//            if (body instanceof String) {
//                return JSONObject.toJSONString(responseResult);
//            }
            return responseResult;
        }

    }
}
